/**
 * 饼图专题图
 */
/**
 * 饼图
 * 说明：能适应单指标、多指标的展示（考虑多指标时可以转变为多条折线图）
 * data = [{
       id: 'pie',
       name: '饼图',
       regioncode: "aaa",
       regionname: "aaa",
       lon: "70.92866163503169",
       lat: "78.830660058696104",
       showThumbnails:false,
       width: '100px',
       heigth: '100px',
       data: [{
           value: 335,
           name: '直接访问'
         },
         {
           value: 310,
           name: '邮件营销'
         },
         {
           value: 234,
           name: '联盟广告'
         },
         {
           value: 135,
           name: '视频广告'
         },
         {
           value: 1548,
           name: '搜索引擎'
         }
        ]
     }]
 *
 */
import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sgis.layer.base';
import styleModify from './echarts.stylemodify'; // 为设置图层的透明度，可见性，zIndex等引入
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
export default {
  activeMap: {}, // 当前活动地图
  pieLayer: '',
  pieLayerInfo: {}, // 图层其他相关信息
  /**
   * 创建地图饼图专题图
   */
  createLayer(map, data) {
    if (!map) {
      return;
    }
    if (!data || !data.data.length) {
      return;
    }
    this.activeMap = map;
    const pieMarkers = this.createMarker(data.data); // 创建好所有marker
    const pieLayer = L.layerGroup(pieMarkers)
      .addTo(map);
    styleModify.onZoom(this.activeMap, pieMarkers); // 为markers绘图添加缩放监听改变z-Index;
    // 此处必须先把容器加到地图上才能加载图表
    this.clickPieIcon();

    this.pieLayer = pieLayer;
    // 将容器加载到地图容器
    this.createCharts(pieMarkers, data.data);
    // 自定义颜色开始
    const layerId = "pie_chart_" + data.id + "_" + +new Date();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, pieLayer._layers, layerId);
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    styleModify.layerOrder[layerId] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    pieLayer.setCustomColor = this.setCustomColor;
    pieLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    pieLayer.setVisible = styleModify.setVisible; // 设置图层可见性
    pieLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    pieLayer.charts = { ...this.charts
    };
    pieLayer.layerId = layerId;
    pieLayer.autoCalgraph = this.autoCalgraph;
    // 自顶替颜色结束
    const pieLayerInfo = {
      name: data.name,
      type: "pie",
      layerId,
      show: data.showThumbnails !== false,
      layer: pieLayer,
      html: this.calgraph(layerId)
    };
    this.pieLayerInfo = pieLayerInfo;
    sgisLayerBase.setOverLayers(pieLayerInfo);
    return pieLayerInfo;
  },
  /**
   * 创建echarts容器
   */
  createMarker(datas) {
    const resultMarkers = [];
    for (let i = 0; i < datas.length; i++) {
      const time = +new Date();
      // 初始化最小宽高开始
      let width = colorPicker.size;
      const data = datas[i];
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      const iconWidth = width + 45;
      const iconHeight = height + 45;
      // 初始化最小宽高结束
      const chartMarker = L.marker([datas[i].lat, datas[i].lon], {
        id: "pie_chart_" + i + time, // 生成id
        pane: styleModify.pane, // 为设置自定义的图层顺序特别设定
        icon: L.divIcon({
          className: "",
          iconSize: [iconWidth, iconHeight],
          html: `
          <div style="box-sizing:border-box;position:relative;z-index='99999'">
          <i class = 'iconfont icon-Refresh' style="position:absolute;right:5px;top:35px;color:${colorPicker.line.axisColor};" refresh='pie_chart_${i}${time}' title='还原'></i>
          <i class = 'iconfont icon-fsux_tubiao_bingtu'
          style = "position:absolute;right:20px;top:35px;color:${colorPicker.line.axisColor}" chart='pie_chart_${i}${time}' title='环形图'></i>
          <div id="pie_chart_${i}${time}" style="width:${width}px;height:${height}px;position:absolute;top:0px;background-color:transparent;z-index='99998';">
          </div>
          </div>
          `
        })
      });
      resultMarkers.push(chartMarker);
    }

    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} pieMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(pieMarkers, datas) {
    const charts = [];
    for (let i = 0; i < datas.length; i++) {
      this.graph = [];
      const chart = echarts.init(document.getElementById(pieMarkers[i].options.id));
      const chartOption = {
        color: datas[i].color ? datas[i].color : colorPicker.color,
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        toolbox: {
          show: true,
          magicType: {
            show: true,
            type: ['line', 'bar']
          }
        },
        series: [{
          name: '数据',
          type: 'pie',
          radius: '50%',
          center: ['50%', '60%'],
          data: datas[i].data,
          labelLine: {
            show: false
          },
          label: {
            show: false
          },
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      chart.setOption(chartOption);
      charts.push({
        id: pieMarkers[i].options.id,
        echart: chart
      });
      /* *计算图例参数 */
      const colors = datas[i].color ? datas[i].color : colorPicker.color;
      for (const key in datas[i].data) {
        const index = key % colors.length;
        const color = colors[index];
        this.graph.push({
          name: datas[i].data[key].name,
          color
        });
      }
    }
    this.charts = charts;
  },
  /**
   * @param {object} {
     pieStyle: ["red", "green", "skyblue", "yellow", "tomato"]
   }
   par
   */
  setCustomColor(layers, pars) {
    let par = {};
    par = {
      ...pars,
      pieStyle: pars.colors
    };
    for (const key in layers.charts) {
      const item = layers.charts[key];
      const option = item.echart.getOption();
      // 设置饼图颜色开始
      if (par.hasOwnProperty('pieStyle')) {
        option.color = par.pieStyle;
      }
      // 设置饼图颜色结束
      item.echart.clear();
      item.echart.setOption(option);
      // 设置图例颜色 开始
      const colors = item.echart.getOption().color;
      const datas = option.series;
      this.graph = [];
      for (const key in datas[0].data) {
        const index = key % colors.length;
        const color = colors[index];
        this.graph.push({
          name: datas[0].data[key].name,
          color
        });
      }
      // 设置图例颜色 结束
    }
    layers.autoCalgraph(layers.layerId, pars.colors);
  }, // 自定义饼图颜色函数
  calLend(datas) {
    const ledend = [];
    for (const item of datas) {
      ledend.push(item.name);
    }
    return ledend;
  },
  /**
   * @param {string} layerId 图层id
   */
  clickPieIcon() {
    const els = document.querySelectorAll('i[chart]');
    for (let i = 0; i < els.length; i++) {
      const el = els[i];
      el.onclick = () => {
        const id = el.getAttribute('chart');
        for (const key in this.charts) {
          if (this.charts[key].id === id) {
            const options = this.charts[key].echart.getOption();
            options.series[0].radius = ['50%', '70%'];
            this.charts[key].echart.setOption(options);
            return;
          }
        }
      };
    }
    // 变换成环形图
    const els_r = document.querySelectorAll('i[refresh]');
    for (let i = 0; i < els_r.length; i++) {
      const el = els_r[i];
      el.onclick = () => {
        const id = el.getAttribute('refresh');
        for (const key in this.charts) {
          if (this.charts[key].id === id) {
            const options = this.charts[key].echart.getOption();
            options.series[0].radius = '55%';
            this.charts[key].echart.setOption(options);
            return;
          }
        }
      };
    }
    // 变换成饼图
  },
  /* *设置图例样式 开始 */
  calgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div style='transform:translateX(-17px)'>
        <div style = 'display:inline-block;width:0px;height:0px;margin:0;padding:0;border-radius:50px;border:15px solid transparent;border-right-color:${this.graph[key].color};transform:translateY(8px)'> </div>
        <div style='display:inline-block;;margin:0;padding:0;padding-left:5px;line-height:30px;'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    return html;
  },
  autoCalgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div>
        <div style = 'display:inline-block;width:0px;height:0px;margin:0;padding:0;border-radius:50px;border:15px solid transparent;border-right-color:${this.graph[key].color};transform:translateY(8px)'> </div>
        <div style='display:inline-block;;margin:0;padding:0;padding-left:5px;line-height:30px;'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  /* *设置图例样式 结束 */
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
